package study.javabasic.Thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author zhangshuhan
 * @date 2019/2/28
 */
public class CyclicBarrierTest {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier=new CyclicBarrier(4);
        TestCyclicBarrier testCyclicBarrier=new TestCyclicBarrier(cyclicBarrier);
        new Thread(testCyclicBarrier,"A").start();
        new Thread(testCyclicBarrier,"B").start();
        new Thread(testCyclicBarrier,"C").start();
        new Thread(testCyclicBarrier,"D").start();
    }

}

class TestCyclicBarrier implements Runnable {

    private CyclicBarrier cyclicBarrier;

    public TestCyclicBarrier(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        System.out.println("线程" + Thread.currentThread().getName() + "===开始写入数据");
        try {
            //模拟写入数据的操作
            Thread.sleep(200);
            System.out.println("线程" + Thread.currentThread().getName() + "===开始写入完毕");
            try {
                cyclicBarrier.await();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程" + Thread.currentThread().getName() + "===开始执行其他任务");

    }
}
